package service

import (
	"ia/common/model/modeladmin"
	"ia/common/storage"
	"ia/common/support"
	"ia/common/support/define"

	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
	"gorm.io/gorm"
)

type AdminButtonService interface {
	Create(ctx iris.Context)
	Delete(ctx iris.Context)
	Update(ctx iris.Context)
	List(ctx iris.Context)
	CodeList(ctx iris.Context)
}

func NewAdminButtonService() *adminButtonService {
	return &adminButtonService{}
}

type adminButtonService struct{}

func (impl *adminButtonService) Create(ctx iris.Context) {
	var (
		code define.Code
		err  error
		in   modeladmin.AdminButton
	)
	if err = ctx.ReadJSON(&in); err != nil {
		goto ERR
	}
	in.CreatorId = ctx.Values().GetInt64Default(define.Uid, 0)
	if err = storage.GDB1.Create(&in).Error; err != nil {
		goto ERR
	}
	support.Ok_(ctx)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (impl *adminButtonService) Delete(ctx iris.Context) {
	var (
		code   define.Code
		err    error
		idList = make([]int, 0)
	)
	if err = ctx.ReadJSON(&idList); err != nil {
		goto ERR
	}

	if err = storage.GDB1.Transaction(func(tx *gorm.DB) error {
		if err = tx.Delete(&modeladmin.AdminButton{}, "id in ?", idList).Error; err != nil {
			return err
		}
		if err = tx.Delete(&modeladmin.AdminMenuButton{}, "bid in ?", idList).Error; err != nil {
			return err
		}
		if err = tx.Model(&modeladmin.AdminRoleMenu{}).Where("bid in ?", idList).Update("bid", 0).Error; err != nil {
			return err
		}
		return nil
	}); err != nil {
		goto ERR
	}
	support.OkTip(ctx, nil)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (impl *adminButtonService) Update(ctx iris.Context) {
	var (
		code define.Code
		err  error
		in   modeladmin.AdminButton
	)
	if err = ctx.ReadJSON(&in); err != nil {
		goto ERR
	}

	if err = storage.GDB1.Save(&in).Error; err != nil {
		goto ERR
	}
	support.Ok_(ctx)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (impl *adminButtonService) List(ctx iris.Context) {
	var (
		code   define.Code
		err    error
		result = make([]*modeladmin.AdminButton, 0)
	)
	if err = storage.GDB1.Find(&result).Error; err != nil {
		goto ERR
	}
	support.Ok(ctx, result)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}

func (impl *adminButtonService) CodeList(ctx iris.Context) {
	var (
		code   define.Code
		err    error
		result = make([]string, 0)
	)
	if err = storage.GDB1.Model(&modeladmin.AdminButton{}).Select("id").Find(&result).Error; err != nil {
		goto ERR
	}
	support.Ok(ctx, result)
	return
ERR:
	golog.Errorf("错误：%s", err)
	support.InternalServerError(ctx, code)
}
